package com.pipayshop.controller;

import com.pipayshop.domain.dto.ShopCartDto;
import com.pipayshop.domain.vo.ShopCartVo;
import com.pipayshop.entity.vo.ResponseVO;
import com.pipayshop.exception.BusinessException;
import com.pipayshop.service.OnlineStoreShopCartService;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author xiaoqiu
 * @date 2024/9/19 14:55
 * @description 网店购物车接口
 */
@RestController
@RequestMapping("/pipayshopapi/shopcart")
@Tag(name  = "网店购物车接口",description  = "网店购物车接口")
@Slf4j
public class OnlineStoreShopCartController {
    @Autowired
    private OnlineStoreShopCartService shopCartService;

    /**
     * 添加网店购物车
     * @param shopCartDto 网店购物车对象
     * @return 网店购物车对象
     */
    @PostMapping("/addShopCart")
    @Operation(summary ="添加商品到网店购物车")
    public ResponseVO<T> addShopCart(@RequestBody ShopCartDto shopCartDto) {
        try {
            return shopCartService.addShopCart(shopCartDto);
        }catch (BusinessException e) {
            throw new BusinessException(e.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            throw new BusinessException("add_to_cart_failed");
        }
    }

    @GetMapping("selectItemCartByIds/{userId}")
    @ApiOperation("根据用户id展示购物车列表")
    public ResponseVO<List<ShopCartVo>> selectShopCartByIds(@PathVariable String userId){
        try {
            List<ShopCartVo> list = shopCartService.selectShopCartByIds(userId);
            return ResponseVO.getSuccessResponseVo(list);
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            throw new BusinessException("get_cart_by_user_id_failed");
        }
    }

    @PostMapping("/deleteShopCart/{userId}")
    @ApiOperation("根据商品id删除购物车商品")
    public ResponseVO deleteShopCart(@RequestBody List<String> cartId, @PathVariable("userId") String userId){
        try {
            int isUpdate = shopCartService.deleteShopCart(userId, cartId);
            if (isUpdate == 0){
                throw new Exception();
            }else {
                return ResponseVO.getSuccessResponseVo("delete_success");
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            throw new BusinessException("delete_failed");
        }
    }
}
